<template>
  <div>
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh" success-text="刷新成功">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :immediate-check="false"
      >
        <ArticleItemVue
          v-for="item in list"
          :key="item.art_id"
          :artItem="item"
          @delItem="delItem"
          @click.native="toDetailPageFn(item.art_id)"
        ></ArticleItemVue>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import ArticleItemVue from '../../../components/ArticleItem.vue'
import { getAllArticleListAPI } from '@/api'
export default {
  name: 'ArticleListVue',
  components: {
    ArticleItemVue
  },
  props: {
    channelId: Number // 文章id
  },
  data () {
    return {
      list: [], // 文章列表数据
      pre_timestamp: Date.now(), // 下一页文章列表第一项
      loading: false, // 上拉加载状态
      finished: false, // 全部加载完成状态
      isLoading: false // 下拉加载状态

    }
  },
  // 创建当前页的文章列表
  async created () {
    const res = await getAllArticleListAPI({
      channel_id: this.channelId,
      timestamp: this.pre_timestamp
    })
    this.list = res.data.data.results
    this.pre_timestamp = res.data.data.pre_timestamp
  },
  methods: {
    // 下拉刷新
    async onLoad () {
      if (this.list.length !== 0) {
        const res = await getAllArticleListAPI({
          channel_id: this.channelId,
          timestamp: this.pre_timestamp
        })
        this.list = [...this.list, ...res.data.data.results]
        this.pre_timestamp = res.data.data.pre_timestamp
        this.loading = false
        if (this.pre_timestamp === null) {
          this.finished = true
        }
      } else {
        this.loading = false
      }
    },
    // 上拉刷新
    async onRefresh () {
      const res = await getAllArticleListAPI({
        channel_id: this.channelId,
        timestamp: Date.now()
      })
      this.list = res.data.data.results
      this.pre_timestamp = res.data.data.pre_timestamp
      this.isLoading = false
    },
    // 删除不感兴趣的文章or举报文章
    delItem (art_id) {
      this.list.splice(this.list.findIndex(item => item.art_id === art_id), 1)
    },
    // 详细页
    toDetailPageFn (id) {
      this.$router.push(`/articleDetail?id=${id}`)
    }

  }
}
</script>

<style>
</style>
